import { Typography, Space, Row, Col, Button, message, Input, Drawer } from 'antd';
import ProCard from '@ant-design/pro-card';
import React, { useState, useRef, useEffect } from 'react';
import { getDvaApp, history, } from 'umi';
import ProForm, {
    ProFormText,
    ProFormCascader,
    ProFormSelect,
    ProFormDatePicker,
    ProFormMoney,
    ProFormSwitch,
    ProFormTimePicker,
} from '@ant-design/pro-form';
import type { ProFormInstance } from '@ant-design/pro-form';
import { PageContainer } from '@ant-design/pro-layout';
import $utils from '@/utils/utils';
import { getStationDetail, updStation } from '@/services/postHouse';
import { getRegionData, getRegionQuery } from '@/services/user';
import moment from 'moment';

const { Title, Paragraph } = Typography;
const userInfo = $utils.getStorage('user_info');

const Detail: React.FC = () => {

    // 解决无法调用dispatch
    const dispatch = getDvaApp()._store.dispatch;
    const formRef = useRef<ProFormInstance>();
    const [cur_id, setCur_id] = useState<string>();
    const [stationDetail, setStationDetail] = useState<any>({});
    const [townList, setTownList] = useState<API.Select[]>();
    const [regionList, setRegionList] = useState<any>();
    const [regionCode, setRegionCode] = useState<string>('');

    const l_state: any = history.location.state;
    if (!cur_id && (!l_state || !l_state?.data)) {
        history.push('/BasicConfig/postHouse');
    }

    const id: string = l_state?.data?.id;
    //  同path更新,只更新state时，通过id重新请求数据
    if (l_state && id && (!cur_id || cur_id !== id)) {
        setCur_id(id);
    }

    const isDetail: boolean = l_state?.status === 'detail';
    const isUpdate: boolean = l_state?.status === 'update';


    useEffect(() => {
        const getSelectData = async () => {
            try {
                const result = await getRegionData();
                setRegionList(result);
            } catch (error) {
                message.error(`${error}`);
            }
        }

        getSelectData();

        const getStationDetails = async () => {
            try {
                const msg = await getStationDetail({ id: cur_id });;
                if (msg.code === 0) {
                    let data = {
                        create_time: msg.body.createTime,
                        open_time: msg.body.openTime,
                        createTime: msg.body.createTime ? moment(msg.body.createTime) : moment(),
                        openTime: msg.body.openTime ? [moment(msg.body.openTime.split('-')[0], moment.HTML5_FMT.TIME), moment(msg.body.openTime.split('-')[1], moment.HTML5_FMT.TIME)] : '',
                        fullName: [msg.body.regionInfo.province, msg.body.regionInfo.city, msg.body.regionInfo.county],
                        regionInfo_name: msg.body.regionInfo.town,
                        smsPrice: Math.round(msg.body.smsPrice) / 100,
                        servicePrice: Math.round(msg.body.servicePrice) / 100,
                        canUseShelf: msg.body.canUseShelf === 1,
                        canUseCab: msg.body.canUseCab === 1,
                        canWithdraw: msg.body.canWithdraw === 1,
                    };

                    data = Object.assign({}, msg.body, data);
                    setRegionCode(msg.body.regionInfo.county);
                    setStationDetail(data);

                    formRef && formRef.current?.resetFields();

                    return;
                }
            } catch (error) {
                console.log(error);
            }
        };

        getStationDetails();
    }, [cur_id]);

    useEffect(() => {
        const getRegion_Query = async () => {
            try {
                const msg = await getRegionQuery({ sessionId: userInfo.sessionId, code: regionCode });
                let new_data: API.Select[] = [];
                if (msg.code === 0) {
                    msg.body.map((item: { code: number, name: string }) => {
                        new_data.push({
                            label: item.name,
                            value: item.code,
                        });
                    });
                    setTownList(new_data);
                    return;
                }
            } catch (error) {
                console.log(error);
            }
        };

        regionCode && getRegion_Query();
    }, [regionCode])


    const updStationDetail = async (params: any) => {
        try {
            const msg = await updStation({ sessionId: userInfo.sessionId, id, ...params });
            if (msg.code === 0) {
                message.success('编辑成功', 1, () => {
                    // 设置当前tab对象
                    $utils.setNewTab(dispatch, { name: '驿站管理', path: '/BasicConfig/postHouse', isTopMenu: true });
                    history.push('/BasicConfig/postHouse');
                });
                return;
            }
        } catch (error) {
            console.log(error);
        }
    }

    return (
        <PageContainer>
            <ProCard style={{ marginTop: 8 }} gutter={8} >
                {JSON.stringify(stationDetail) !== '{}' ? <ProForm
                    labelCol={{ span: 6 }}
                    wrapperCol={{ span: 18 }}
                    layout={"horizontal"}
                    formRef={formRef}
                    onFinish={async (values) => {
                        try {
                            const params: any = { ...values };
                            params.openTime = values.openTime.join('-');
                            values.regionInfo_name ? params.regionCode = values.regionInfo_name : params.regionCode = [...values.fullName].slice(-1);
                            params.canUseShelf = values.canUseShelf ? 1 : 2;
                            params.canWithdraw = values.canWithdraw ? 1 : 2;
                            params.canUseCab = values.canUseCab ? 1 : 2;
                            params.servicePrice = Math.round(values.servicePrice * 100);
                            params.smsPrice = Math.round(values.smsPrice * 100);
                            await updStationDetail(params);
                        } catch (error) {
                            console.error(error);
                        }
                    }}
                    initialValues={stationDetail}
                    validateTrigger={'onBlur'}
                    params={{ uid: userInfo.uid, id }}
                    submitter={{
                        render: (props, doms) => {

                            return [
                                <Space style={{ marginLeft: '6.4166666%' }}>
                                    {isUpdate && <Button type="primary" htmlType="submit">保存</Button>}
                                    <Button onClick={() => {
                                        // 设置当前tab对象
                                        $utils.setNewTab(dispatch, { name: '驿站管理', path: '/BasicConfig/postHouse', isTopMenu: true });
                                        history.push('/BasicConfig/postHouse');
                                    }}>取消</Button>
                                </Space>
                            ]
                        }
                    }}
                >
                    <Title level={4} style={{ marginBottom: 26 }}>基本信息</Title>
                    <Row>
                        <Col span={10}>
                            <ProFormText
                                disabled={isDetail}
                                name="name"
                                label={'驿站名称'}
                                rules={[
                                    {
                                        required: true,
                                    },
                                    {
                                        max: 20,
                                    },
                                ]}
                            />
                        </Col>
                        <Col span={10}>
                            <ProFormCascader
                                disabled={isDetail}
                                name="fullName"
                                label={'所属地区'}
                                fieldProps={{
                                    options: regionList,
                                    onChange: (value: any) => {
                                        const arr = [...value];
                                        setRegionCode(arr.pop());
                                    },
                                }}
                                rules={[
                                    {
                                        required: true,
                                    }
                                ]}
                            />
                        </Col>
                    </Row>
                    <Row>
                        <Col span={10}>
                            <ProFormText
                                disabled={isDetail}
                                name="contactName"
                                label={'联系人'}
                                fieldProps={{
                                    maxLength: 10,
                                }}
                                rules={[
                                    {
                                        required: true,
                                    }
                                ]}
                            />
                        </Col>
                        <Col span={10}>
                            <ProFormSelect
                                disabled={isDetail}
                                name="regionInfo_name"
                                label={'所属街道'}
                                fieldProps={{
                                    options: townList,
                                }}
                                rules={[
                                    {
                                        required: true,
                                    }
                                ]}
                            />
                        </Col>
                    </Row>
                    <Row>
                        <Col span={10}>
                            <ProFormText
                                disabled={isDetail}
                                name="contactPhone"
                                label={'联系电话'}
                                fieldProps={{
                                    maxLength: 11,
                                }}
                                rules={[
                                    {
                                        required: true,
                                    },
                                    {
                                        max: 11,
                                    }
                                ]}
                            />
                        </Col>
                        <Col span={10}>
                            <ProFormSelect
                                disabled={isDetail}
                                name="type"
                                label={'驿站类型'}
                                options={[
                                    { label: '校园', value: 1 },
                                    { label: '社区', value: 2 },
                                ]}
                                rules={[
                                    {
                                        required: true,
                                    }
                                ]}
                            />
                        </Col>
                    </Row>
                    <Row>
                        <Col span={10}>
                            <ProFormTimePicker.RangePicker
                                disabled={isDetail}
                                name="openTime"
                                label={'营业时间'}
                                fieldProps={{
                                    format: 'HH:mm',
                                }}
                                rules={[
                                    {
                                        required: true,
                                    }
                                ]}
                            />
                        </Col>
                        <Col span={10}>
                            <ProFormSelect
                                disabled={isDetail}
                                name="status"
                                label={'驿站状态'}
                                options={[
                                    { label: '运营中', value: 1 },
                                    { label: '已关闭', value: 2 },
                                ]}
                                rules={[
                                    {
                                        required: true,
                                    }
                                ]}
                            />
                        </Col>
                    </Row>
                    <Row>
                        <Col span={10}>
                            <ProFormText
                                disabled={isDetail}
                                name="address"
                                label={'详细地址'}
                                fieldProps={{
                                    maxLength: 25,
                                }}
                                rules={[
                                    {
                                        required: true,
                                    },
                                    {
                                        max: 25,
                                    }
                                ]}
                            />
                        </Col>
                    </Row>
                    <Row>
                        <Col span={10}>
                            <ProFormText
                                disabled={true}
                                name="createPhone"
                                label={'注册手机号'}
                            />
                        </Col>
                        <Col span={10}>
                            <ProFormDatePicker
                                disabled={true}
                                name="createTime"
                                label={'注册时间'}
                                rules={[
                                    {
                                        required: true,
                                    }
                                ]}
                            />
                        </Col>
                    </Row>
                    <Title level={4} style={{ marginBottom: 26 }}>费用设置</Title>
                    <Row>
                        <Col span={10}>
                            <ProFormMoney
                                disabled={isDetail}
                                width={'xs'}
                                label="平台费"
                                name="servicePrice"
                                rules={[
                                    {
                                        required: true,
                                    },
                                    ({ getFieldValue }) => ({
                                        validator(_, value) {
                                            console.log(value, getFieldValue('smsPrice'));
                                            if (value + getFieldValue('smsPrice') > 5) {
                                                return Promise.reject(new Error('平台费与短信费相加不能超过5.00元'))
                                            }
                                            return Promise.resolve();
                                        }
                                    })
                                ]}
                            />
                        </Col>
                        <Col span={10}>
                            <ProFormMoney
                                disabled={isDetail}
                                width={'xs'}
                                label="短信费"
                                name="smsPrice"
                                rules={[
                                    {
                                        required: true,
                                    },
                                    ({ getFieldValue }) => ({
                                        validator(_, value) {
                                            if (value + getFieldValue('servicePrice') > 5) {
                                                return Promise.reject(new Error('平台费与短信费相加不能超过5.00元'))
                                            }
                                            return Promise.resolve();
                                        }
                                    }),
                                ]}
                            />
                        </Col>
                    </Row>
                    <Title level={4} style={{ marginBottom: 26 }}>业务设置</Title>
                    <Row style={{ marginBottom: 26 }}>
                        <Col span={10}>
                            <ProFormSwitch
                                disabled={isDetail}
                                width={'md'}
                                name="canUseShelf"
                                label="货架入库功能"
                                checkedChildren="开启"
                                unCheckedChildren="禁用"
                                rules={[
                                    {
                                        required: true,
                                    }
                                ]}
                            />
                        </Col>
                        <Col span={10}>
                            <ProFormSwitch
                                disabled={isDetail}
                                width={'md'}
                                name="canWithdraw"
                                label="提现功能"
                                checkedChildren="开启"
                                unCheckedChildren="禁用"
                                rules={[
                                    {
                                        required: true,
                                    }
                                ]}
                            />
                        </Col>
                        <Col span={10}>
                            <ProFormSwitch
                                disabled={isDetail}
                                width={'md'}
                                name="canUseCab"
                                label="柜体入库功能"
                                checkedChildren="开启"
                                unCheckedChildren="禁用"
                                rules={[
                                    {
                                        required: true,
                                    }
                                ]}
                            />
                        </Col>
                    </Row>
                    <Typography style={{ paddingLeft: '6.4166666%', paddingBottom: 26 }}>
                        <Paragraph strong={true}>创建人: {stationDetail?.createUserName}</Paragraph>
                        <Paragraph strong={true}>创建时间: {stationDetail?.create_time}</Paragraph>
                        <Paragraph strong={true}>最新修改人: {stationDetail?.updateUserName || stationDetail?.createUserName}</Paragraph>
                        <Paragraph strong={true}>修改时间: {stationDetail?.updateTime}</Paragraph>
                    </Typography>
                </ProForm> : ''}
            </ProCard>
        </PageContainer>
    );
};

export default Detail;
